package com.vpen.blog.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vpen.blog.common.ReturnResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * -@Version 1.0
 * -@Author:Vpen
 * -@Date:2021/7/8 22:52
 * -@Content: 当接口没有权限访问时，自定义返回
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        ReturnResult result = ReturnResult.getInstance().fail("太菜了，没有权限");
        result.setCode(403);
        out.write(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();

    }
}
